package com.imooc.controller.center;

import com.imooc.controller.BaseController;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.center.CenterUserBO;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.resource.FileUpload;
import com.imooc.service.center.CenterUserService;
import com.imooc.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 顾志杰
 * @Date: 2019/12/5
 * @Time: 10:45
 */
@Api(value = "用户信息接口", tags = {"用户信息接口"})
@RestController
@RequestMapping("userInfo")
public class CenterUserController extends BaseController {
    @Autowired
    private CenterUserService centerUserService;
    @Autowired
    private FileUpload fileUpload;
    @Autowired
    private FastdfsService fastdfsService;

    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", httpMethod = "POST")
    @PostMapping("update")
    public IMOOCJSONResult update(@ApiParam(name = "userId", value = "用户id", required = true)
                                  @RequestParam String userId,
                                  @RequestBody @Valid CenterUserBO centerUserBO,
                                  BindingResult result,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {
        // 判断BindingResult是否保存错误的验证信息，如果有，则直接return
        if (result.hasErrors()) {
            Map<String, String> errorMap = getErrors(result);
            return IMOOCJSONResult.errorMap(errorMap);
        }
        Users users = centerUserService.updateUserInfo(userId, centerUserBO);
        setNullProperty(users);


        // 增加令牌token，会整合进redis，分布式会话
        UsersVO usersVO = conventUsersVO(users);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(usersVO), true);

        return IMOOCJSONResult.ok();
    }

    @ApiOperation(value = "用户头像修改静态文件", notes = "用户头像修改", httpMethod = "POST")
    @PostMapping("uploadFace")
    public IMOOCJSONResult uploadFace(@ApiParam(name = "userId", value = "用户id", required = true)
                                  @RequestParam String userId,
                                  @ApiParam(name = "file", value = "用户头像", required = true)
                                          MultipartFile file,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {
        // 定义头像保存地址
//        String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUpload.getImageUserFaceLocation();
        //在路径上为每一个用户增加一个userid 用于区别不同用户上传
        String uploadPathPrefix = File.separator + userId;
        if (file == null) return IMOOCJSONResult.errorMsg("文件不能为空");
        FileOutputStream fileOutputStream = null;
        try {
            //获得文件上传的文件名称
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                //文件重命名
                String[] fiseNameArr = fileName.split("\\.");
                //获取文件的后缀名
                String suffix = fiseNameArr[fiseNameArr.length - 1];
                // face-{userid}.png
                //文件名称重组 覆盖式上传 如果增量式需要拼接时间
                String newFileName = "face-" + userId + "." + suffix;
                //上传头像最终的保存的位置
                String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
                //用于提供给web访问的地址
                uploadPathPrefix += ("/"+newFileName);
                //创建文件
                File outFile = new File(finalFacePath);
                if (outFile.getParentFile() != null) {
                    //创建文件夹 mkdirs会递归生成文件夹
                    outFile.getParentFile().mkdirs();
                }
                //文件输出保存到目录
                fileOutputStream = new FileOutputStream(outFile);
                //获取文件输入流
                InputStream inputStream = file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //更新用户头像到数据库
        String imageServerUrl = fileUpload.getImageServerUrl();
        // 由于浏览器可能存在缓存的情况，所以在这里，我们需要加上时间戳来保证更新后的图片可以及时刷新
        String finalUserFaceUrl = imageServerUrl + uploadPathPrefix
                + "?t="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        Users userResult = centerUserService.updateUserFace(userId,finalUserFaceUrl);
        userResult = setNullProperty(userResult);

        // 增加令牌token，会整合进redis，分布式会话
        UsersVO usersVO = conventUsersVO(userResult);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(usersVO), true);
        return IMOOCJSONResult.ok();
    }

    @ApiOperation(value = "用户头像修改fastdfs", notes = "用户头像修改", httpMethod = "POST")
    @PostMapping("uploadFaceFastdfs")
    public IMOOCJSONResult uploadFaceFastdfs(@ApiParam(name = "userId", value = "用户id", required = true)
                                      @RequestParam String userId,
                                      @ApiParam(name = "file", value = "用户头像", required = true)
                                              MultipartFile file,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {
        if (file == null) {
            return IMOOCJSONResult.errorMsg("文件不能为空");
        }
        try {
            String url = fastdfsService.upload(file);
            //更新用户头像到数据库
            String imageServerUrl = fileUpload.getHost();
            // 由于浏览器可能存在缓存的情况，所以在这里，我们需要加上时间戳来保证更新后的图片可以及时刷新
            String finalUserFaceUrl = imageServerUrl + url;
            Users userResult = centerUserService.updateUserFace(userId,finalUserFaceUrl);
            setNullProperty(userResult);
            // 增加令牌token，会整合进redis，分布式会话
            UsersVO usersVO = conventUsersVO(userResult);
            CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(usersVO), true);
            return IMOOCJSONResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return IMOOCJSONResult.errorMsg("头像上传失败");
        }

    }

    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            // 发生验证错误所对应的某一个属性
            String errorField = error.getField();
            // 验证错误的信息
            String errorMsg = error.getDefaultMessage();

            map.put(errorField, errorMsg);
        }
        return map;
    }

    private Users setNullProperty(Users users) {
        users.setPassword(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setBirthday(null);
        return users;
    }
}
